const db = require("../../lib/db");

//获取评论
exports.getCommentPage = (pageSize, nowPage) => {
    let _sql = `SELECT * FROM comment order by id desc limit ?, ?`;
    let params = [(nowPage - 1) * pageSize, pageSize];
    return db.queryWithPool(_sql, params);
};
//根据文章id获取一级评论
exports.getCommentByArticleId = (articleId, pageSize, nowPage) => {
  let _sql = `SELECT * FROM comment WHERE article_id = ? order by id desc limit ?, ?`;
  let params = [articleId, (nowPage - 1) * pageSize, pageSize];
  return db.queryWithPool(_sql, params);
};

// 新增评论
exports.addComment = (data) => {
  let _sql = `INSERT INTO comment SET ?`;
  return db.queryWithPool(_sql, [data]);
};

//获取总评论数或某篇文章的评论数
exports.getCommentCount = (articleId) => {
  let _sql;
  let params = [];
  if (articleId == -1) {
    _sql = `SELECT count(*) AS count FROM comment`;
  } else {
    _sql = `SELECT count(*) AS count FROM comment WHERE article_id = ?`;
    params = [articleId];
  }
  return db.queryWithPool(_sql, params);
};

//评论状态更新
exports.updateCommentStatus = (id) => {
  let _sql = `UPDATE comment SET isread = 1 WHERE id = ?`;
  return db.queryWithPool(_sql, [id]);
};

//删除顶级评论
exports.deleteComment = (id) => {
  let _sql = `DELETE FROM comment WHERE id = ?`;
  // 递归删除子评论
  exports.deleteCommentKidsByroot_id(id);
  // 递归删除三级评论
  exports.deleteCommentKidsByparent_id(id);
  return db.queryWithPool(_sql, [id]);
};
//删除二级评论
exports.deleteCommentKidsByroot_id = (id) => {
  let _sql = `DELETE FROM comment WHERE root_id = ?`;
  return db.queryWithPool(_sql, [id]);
};
//删除三级评论
exports.deleteCommentKidsByparent_id = (id) => {
  let _sql = `DELETE FROM comment WHERE parent_id = ?`;
  return db.queryWithPool(_sql, [id]);
};



//举报评论
exports.complaintComment = (id) => {
  let _sql = `UPDATE comment SET complaint = complaint + 1 WHERE id = ?`;
  return db.queryWithPool(_sql, [id]);
};